package hotel.quartz.oversea.job.switchs;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.dto.master.CompareHotelBasicRoomDto;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 创建子物理房型定时器
 *
 * @author HuangT
 * @date 2020/6/30 11:19
 */
@Slf4j
public class SwitchCreateBasicRoomJob implements BaseJob {
    @Autowired
    private RestTemplate restTemplate;
    private final String timestamp = "Scbrj" + System.currentTimeMillis();

    /**
     * 创建子物理房型定时器，不停跑，执行频率6-8每
     * <p>
     * 每次创建一个子物理房型  6-8秒调用 接口限制
     * <p>
     * 根据sys_compare_hotel_basic_room表获取需创建子物理房型的房型数据，创建成功后需更新create_state状态==》》如果接口返回接口认证失败，签名验证失败
     * 则需要还原，让定时器下次可以再执行他
     *
     * @param jobExecutionContext
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        log.info("Switch Create Basic Room Job >>>>>>>> 携程创建子物理房型执行时间: {}, {}", timestamp, DateUtil.now());
        String accessToken = "";
        /*String switchsHost = CommonUrlConstants.SWITCHS_HOST;*/
        String switchsHost = CommonUrlConstants.SWITCHS_ONLINE_HOST;
        String compareHost = CommonUrlConstants.COMPARE_HOST;
        //对比系统接口
        String basicRoomGetUrl = compareHost + UrlSwitchsEnums.basicRoom.GET.getValue();
        //携程接口
        String basicRoomSaveUrl = switchsHost + UrlSwitchsEnums.basicRoom.SAVE.getValue();// + "?access_token=" + accessToken;
        //对比系统接口
        String basicRoomBackUrl = compareHost + UrlSwitchsEnums.basicRoom.BACK.getValue();// + "?access_token=" + accessToken;
        //获取已对比、未创建子房型的房型数据
        Result result = getBasicRoomInfo(basicRoomGetUrl, accessToken);
        if (result.getCode() == CommonConstants.SUCCESS && null != result.getData()) {
            CompareHotelBasicRoomDto hotelBasicRoomDto = JacksonUtil.objToBean(result.getData(), CompareHotelBasicRoomDto.class);
            log.info("Switch Create Basic RoomJob {} >>>>>>>> 创建子物理房型 hotelBasicRoomDto={}", JSON.toJSONString(hotelBasicRoomDto));
            //创建子物理房型
            Result basicRoom = createOneBasicRoom(basicRoomSaveUrl, hotelBasicRoomDto);
            if(null != basicRoom){
                if (basicRoom.getCode() == CommonConstants.SUCCESS) {
                }else{
                    if(null != basicRoom.getMsg() && basicRoom.getMsg().toString().contains("接口认证失败")
                            || basicRoom.getCode() == -1
                            || basicRoom.getCode() == 1002
                            || basicRoom.getCode() == 1003
                            || basicRoom.getCode() == 1004){
                        //重置为0 让定时器下次进来继续执行调用创建
                        updateBasicRoom(hotelBasicRoomDto, basicRoomBackUrl,0, JSON.toJSONString(basicRoom));
                    }else{
                        //失败2，该房型不符合创建
                        updateBasicRoom(hotelBasicRoomDto, basicRoomBackUrl,2, JSON.toJSONString(basicRoom));
                    }
                }
            }
        }else{
            log.info("Switch Create Basic RoomJob {} >>>>>>>> 创建子物理房型,未获取到需创建子物理房型的房型数据 程序return {}", timestamp, hotel.base.oversea.utils.DateUtil.getCurrTime());
        }
        log.info("Switch Create Basic RoomJob >>>>>>>> 创建子物理房型结束时间: {},{}", timestamp, DateUtil.now());
    }


    /**
     * <H1>创建子房间失败后，更新数据库</H1>
     *
     * @param hotelBasicRoomDto
     * @param basicRoomBackUrl
     * @return void
     * @author HuangT
     * @date 2020/7/1 20:44
     */
    private void updateBasicRoom(CompareHotelBasicRoomDto hotelBasicRoomDto, String basicRoomBackUrl, Integer createState, String createStateRemark) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", hotelBasicRoomDto.getId());
        map.put("createState",createState);
        map.put("createStateRemark",createStateRemark);
        log.info("Switch Create Basic Room Job {} 创建子物理房型定时器 进入方法 updateBasicRoom:{}",timestamp, JSON.toJSONString(map));
        //发起请求
        Result response = JobRestTemplateUtils.post(basicRoomBackUrl, JSON.toJSONString(map),restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.info("Switch Create Basic Room {} 创建子物理房型  updateBasicRoom  异常：", JSON.toJSONString(response));
        }

    }

    /**
     * <H1>创建子物理房型</H1>
     *
     * @param basicRoomSaveUrl
     * @param hotelBasicRoomDto
     * @return void
     * @author HuangT
     * @date 2020/7/1 14:09
     * @version  20200722 qiuyy  接口要求增加两个参数 mtHotelId  mtRoomId
     */
    private Result createOneBasicRoom(String basicRoomSaveUrl, CompareHotelBasicRoomDto hotelBasicRoomDto) {
        Map<String, String> map = new HashMap<>();
        map.put("masterBasicRoomId", hotelBasicRoomDto.getSwitchHotelRoomId());
        map.put("childHotelId", String.valueOf(hotelBasicRoomDto.getSwitchHotelId()));
        map.put("masterHotelId", String.valueOf(hotelBasicRoomDto.getSwitchMasterHotelId()));
        map.put("mtHotelId", String.valueOf(hotelBasicRoomDto.getMtHotelId()));
        map.put("mtRoomId", String.valueOf(hotelBasicRoomDto.getMtRoomId()));
        log.info("Switch Create Basic Room Job {} 创建子物理房型定时器 进入方法 createOneBasicRoom:{}",timestamp, JSON.toJSONString(map));
        //发起请求
        Result response = JobRestTemplateUtils.post(basicRoomSaveUrl, JSON.toJSONString(map),restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.info("Switch Create Basic Room Job {} 创建子物理房型定时器 进入方法 createOneBasicRoom 返回失败 : {}",timestamp, JSON.toJSONString(response));
        }
        return response;
    }

    /**
     * <H1>获取已对比房型数据</H1>
     *
     * @param basicRoomGetUrl
     * @param accessToken
     * @return java.lang.String
     * @author HuangT
     * @date 2020/7/1 11:55
     */
    private Result getBasicRoomInfo(String basicRoomGetUrl, String accessToken) {
        log.info("Switch Create Basic Room Job {} 创建子物理房型定时器 进入方法 getBasicRoomInfo",timestamp);
        Map map = new HashMap();
//        map.put("access_token",accessToken);

        //发起请求
        Result response = JobRestTemplateUtils.get(basicRoomGetUrl,map,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.info("Switch Create Basic Room Job {} 获取已比对房型信息 getBasicRoomInfo 请求返回失败: {}",timestamp, JSON.toJSONString(response));
        }
        return response;
    }
}
